package com.wuwei.elearning.question.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wuwei.elearning.service.CacheService;
import com.wuwei.elearning.enumPackage.Constant;
import com.wuwei.elearning.question.domain.Ppt;
import com.wuwei.elearning.question.mapper.PptMapper;
import com.wuwei.elearning.question.service.PptService;
import com.wuwei.elearning.utils.MinioUtil;
import com.wuwei.elearning.utils.result.Result;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/elearning/ppt")
@CrossOrigin
public class PptController {

    @Resource
    private MinioUtil minioUtil;

//    @GetMapping("preview")
//    public void download(@RequestParam("file") String filePath, HttpServletResponse response) {
//        minioUtil.download(filePath,response);
//    }
//
//    @GetMapping("download")
//    public ModelAndView download(@RequestParam("file") String filePath, ModelAndView model) {
//        model.addObject("filePath",filePath);
//        model.setViewName("/preview");
//        return model;
//    }


    @Resource
    private PptMapper pptMapper;

    @GetMapping("list/{name}/{currentPage}/{pageSize}")
    public Result<List<Ppt>> getPpts(@PathVariable("name")String name, @PathVariable("currentPage") int currentPage,
                                           @PathVariable("pageSize") int pageSize) {
//        LambdaQueryWrapper<Ppt> wrapper = new LambdaQueryWrapper<>();
//        wrapper.like(!"_".equals(name),Ppt::getName,name);
//        IPage<Ppt> page = new Page<>();
//        page.setCurrent(currentPage);
//        page.setSize(pageSize);
//        IPage<Ppt> questionIPage = pptMapper.selectPage(page, wrapper);
//        List<Ppt> ppts = questionIPage.getRecords();
        List<Ppt> ppts = new ArrayList<>();
        int skip = (currentPage - 1) * pageSize;
        if (!name.equals("_")) {
            ppts = pptMapper.myQuerySelect(name,pageSize,skip);
        }else {
            ppts = pptMapper.mySelect(pageSize,skip);
        }

        for (Ppt  ppt : ppts) {
            String upload = ppt.getUrl();
            // 构建Redis键
            String redisKey = Constant.MINIO_PDF + upload;
            // 尝试从Redis获取
            String url = cacheService.getPdf(upload, redisKey);
            ppt.setUrl(url);
        }
        return Result.ok(ppts);
    }

    @GetMapping("getTotal/{name}")
    public Result<Long> getTotal(@PathVariable("name")String name){
        LambdaQueryWrapper<Ppt> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(!"_".equals(name),Ppt::getName,name);
        Long count = pptMapper.selectCount(wrapper);
        return Result.ok(count);
    }

    @PostMapping("deleteByURL")
    public Result<String> deleteByURL(@RequestBody Ppt ppt) {
        pptService.myDelete(ppt);
        return Result.ok("删除成功！");
    }

    @SneakyThrows
    @PostMapping("uploadPPT")
    public void uploadPPT(MultipartFile file, HttpServletResponse response){
        if (file.getSize() != 0) {
            String originalFilename = file.getOriginalFilename();
            String fileName = null;
            int indexOfPoint = 0;
            if (originalFilename != null) {
                indexOfPoint = originalFilename.lastIndexOf(".");
                if (indexOfPoint!=-1) {
                    fileName = originalFilename.substring(0, indexOfPoint);
                } else {
                    Result.sendErrorResponse(response, "文件名不合法！", HttpServletResponse.SC_BAD_REQUEST);
                    return;
                }
            } else {
                Result.sendErrorResponse(response, "文件名不合法！", HttpServletResponse.SC_BAD_REQUEST);
                return;
            }

            LambdaQueryWrapper<Ppt> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Ppt::getName,originalFilename);
            Long count = pptMapper.selectCount(wrapper);
            if (count > 0) {
                Result.sendErrorResponse(response,  "文件名重复", HttpServletResponse.SC_BAD_REQUEST);
                return;
            }

            String suffix = originalFilename.substring(indexOfPoint + 1);
            String upperCase = suffix.toUpperCase();
            String ppt = "ppt".toUpperCase();
            String pptx = "pptx".toUpperCase();
            if (!ppt.equals(upperCase)&&!pptx.equals(upperCase)) {
                Result.sendErrorResponse(response,"请选择ppt或pptx格式的课件！",HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
            pptService.insert(file);
        } else {
            Result.sendErrorResponse(response,"您没有上传任何文件", HttpServletResponse.SC_BAD_REQUEST);
        }
    }

    @Resource
    private PptService pptService;

    @Resource
    private CacheService cacheService;

    @GetMapping("getAll")
    public Result<List<Ppt>> getAll(){
        LambdaQueryWrapper<Ppt> wrapper = new LambdaQueryWrapper<>();
        wrapper.isNotNull(Ppt::getUrl)
                .ne(Ppt::getUrl, "");  // 添加url不为空字符串的条件
        List<Ppt> ppts = pptMapper.selectList(wrapper);

        return Result.ok(ppts);
    }

    @GetMapping("getById/{id}")
    public Result<Ppt> getById(@PathVariable("id") Long id){
        return Result.ok(pptMapper.selectById(id));
    }
}
